/*
 * @Author: your name
 * @Date: 2022-02-21 08:39:57
 * @LastEditTime: 2022-02-21 14:27:54
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /zxd/dome_vue/src/store/index.js
 */
import { createStore } from 'vuex'
import Cookies from 'js-cookie'

import {myLogin} from '../api/gyf/login'
import {fuilterRouter} from '../utils/filterRouter'
import {newRouter} from '../router/userRouter'
import router from '../router';

export default createStore({
  state: {
    user: Cookies.get('user') || {}, // 用户信息
    token: Cookies.get('token') || '',
    author: Cookies.get('author') || '', //  用户唯一标识
    routerList: []
  },
  mutations: {
    user(state, payload) {
      state.user = payload.user;
      state.token = payload.token;
      Cookies.set('token', payload.token);
      Cookies.set('user', payload.user);
      Cookies.set('author', payload.user.author);
    },
    // 获取最新的路由表
    getRouter(state, payload) {
      state.routerList = payload;
    }
  },
  actions: {
    async LOGIN({commit, dispatch}, payload) {
      const { data } = await myLogin('/login', payload);
      console.log(data,"token");
      // 先要获取所有权限路由
      await dispatch('ROUTER_LIST', data.user.author);
      // 存储token
      await commit('user', data.token);
    },
    // 获取路由并设置动态路由
    async ROUTER_LIST ({commit, dispatch}, payload) {
      // 获取当前权限的路由
      const routers = fuilterRouter(newRouter, payload);
      // 追加路由
      routers.forEach(item => {
        router.addRoute(item);
      })
      console.log(routers);
      // 跳路由
      router.push(routers[0].path);
      await commit('getRouter', routers);
    }
  },
  modules: {
  }
})
